package com.chen.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.chen.dto.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: chen
 * @Date: 2021/4/22 2:18 PM
 * @Version 1.0
 */
@RestController
@Api(tags = "文件上传控制器")
public class FileController {

    @Autowired
    private OSS ossClient;

    //在阿里云上创建的bucket
    @Value("${oss.bucket.name:coin-exchange-qf}")
    private String bucketName;

    //外网访问的域名
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endPoint;

    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;

    /**
     * 把文件存在阿里云oss
     * ossClient.putObject(bucketName【阿里云上创建的】,文件名，文件）
     *
     * @param file
     * @return
     * @throws IOException
     */
    @ApiOperation(value = "上传文件")
    @PostMapping("/image/AliYunImgUpload")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "你要上传的文件")
    })
    public R<String> upload(@RequestParam(value = "file") MultipartFile file) throws IOException {

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String format = simpleDateFormat.format(date);

        String fileName = format + "/" + UUID.randomUUID().toString().replaceAll("-", "");

        ossClient.putObject(bucketName, fileName, file.getInputStream());
        return R.ok("http://" + bucketName + "." + endPoint + "/" + fileName);
    }

    @GetMapping("/image/pre/upload")
    @ApiOperation(value = "获取一个上传的票据")
    public R<Map<String, String>> asyncUpload() {
        String dir = DateUtil.today().replaceAll("-", "/");
        Map<String, String> uploadPolicy = getUploadPolicy(30L, 3 * 1024 * 1024L, dir, "http://chen.vipgz1.idcfengye.com");
        return R.ok(uploadPolicy);
    }

    /**
     * 获取上传的票据
     *
     * @param expireTime  票据的过期时间
     * @param dir         文件上传的文件夹
     * @param maxFileSize 上传文件的最大体积
     * @param callbackUrl 前端把文件上传成功后的回调地址
     * @return 票据
     */
    private Map<String, String> getUploadPolicy(Long expireTime, Long maxFileSize, String dir, String callbackUrl) {
        // 返回给前端的值
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        Date expiration = new Date(expireEndTime); // 过期时间
        // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
        PolicyConditions policyConds = new PolicyConditions();
        // 设置上传的大小 ,最大为3M
        policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 3 * 1024 * 1024);
        // 上传的到那个文件夹
        policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
        try {
            // 生成一个票据
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);

            // 对票据加密
            byte[] binaryData = new byte[0];

            binaryData = postPolicy.getBytes("utf-8");

            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);

            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", "https://" + bucketName + "." + endPoint); // host的格式为 https://bucketname.endpoint
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return respMap;
    }
}
